package com.youlai.system.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.system.converter.AccountConverter;
import com.youlai.system.mapper.AccountMapper;
import com.youlai.system.model.entity.Account;
import com.youlai.system.model.query.AccountQuery;
import com.youlai.system.model.vo.AccountPageVO;
import com.youlai.system.service.AccountService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    private final AccountConverter  accountConverter;

    public AccountServiceImpl(AccountConverter accountConverter) {
        this.accountConverter = accountConverter;
    }

    @Override
    public boolean deleteAccount(String idsStr) {
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "删除的用户数据为空");
        // 逻辑删除
        List<Long> ids = Arrays.stream(idsStr.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        return this.removeByIds(ids);
    }

    /*
    分页查询
    LambdaQueryWrapper<>()
    eq：等于
    ne：不等于
    gt：大于
    ge：大于等于
    lt：小于
    le：小于等于
    like：模糊匹配
    notLike：不模糊匹配
    in：在集合中
    notIn：不在集合中
    isNull：为空
    isNotNull：不为空
    orderByAsc：升序排序
     */
    @Override
    public Page<AccountPageVO> getAccountPage(AccountQuery accountQuery) {

        //查询参数
        int pageNum = accountQuery.getPageNum();
        int pageSize = accountQuery.getPageSize();
        String keywords = accountQuery.getKeywords();

        //查询数据
        Page<Account> accountPage = this.page(
                new Page<>(pageNum,pageSize),
                new LambdaQueryWrapper<Account>()
                        //keywords 有效性判断
                        //.like 模糊查找 username
                        .like(StrUtil.isNotBlank(keywords), Account::getUsername,keywords)
                        //需要返回的字段
                        .select(Account::getId,Account::getUsername, Account::getPassword,Account::getUrl)
        );

        //实体转换
        Page<AccountPageVO>  pageResult = accountConverter.entity2Page(accountPage);
        return pageResult;
    }
}
